#!/usr/bin/env groovy

import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import groovy.transform.Field

//global variable
@Field String GITURL = "https://git.xxxxxx.com.cn"
// @Field String PRIVATE_TOKEN="1qfBxwCzmLRknsuFZQXs"

def sendGetRequest(String apiUrl)
{
    def connection = new URL("${GITURL}/${apiUrl}").openConnection() as HttpURLConnection
    //必须是GET方法
    connection.setRequestMethod("GET")
    connection.setRequestProperty('User-Agent', 'groovy-'.concat(GroovySystem.getVersion()))
    connection.setRequestProperty('Accept', 'application/json')
    //必须设置PRIVATE-TOKEN，不然返回404状态
    connection.setRequestProperty('PRIVATE-TOKEN', "${GITLAB_API_TOKEN}")
    def response = connection.inputStream.text
//    println(response.toString())
    return response
}

def jsonParsing(String result)
{
    //json处理
    def slurper = new JsonSlurper()
    def jsonText = slurper.parseText(JsonOutput.prettyPrint(result.toString()))
    return jsonText
}

def getEmailList(String GIT_URL)
{
    //gitlabSourceRepoHomepage= "https://git.xxxxxx.com.cn/smartconstruction/platform-frontend"
    //gitlabSourceRepoHomepage= "https://git.xxxxxx.com.cn/aug-ops/jenkins-pipeline/spring-boots-docker"

    String[] keys;  
    if (GIT_URL.contains(".git"))
    {
        keys = GIT_URL.substring(0,GIT_URL.indexOf(".git")).split(':')[1].split('/') //截取 group+project
    }
    else
    {
        keys = GIT_URL.split('/')[3..-1] //截取 group+project
    }
    //println keys  //[aug-ops, jenkins-pipeline, spring-boots-docker] OR [smartconstruction, platform-frontend] 
    
    groupName=keys[0]
    if (keys.length <3)
    {
        projectName=keys[1]
    }
    else
    {
        projectName=keys[1]+"%2F"+keys[2]
    }

    StringBuilder emailList=new StringBuilder()
    // 1. 根据project name得到project id
    def responseProject=sendGetRequest("/api/v4/projects/${groupName}%2F${projectName}")
    def jsonProject=jsonParsing(responseProject)
    def projectID=jsonProject.id

    // 2. 根据project id得到 project member detail
    def responseMembers=sendGetRequest("/api/v4/projects/${projectID}/members")
    def jsonMembers=jsonParsing(responseMembers)
    def membersID=jsonMembers.id as String[]

    // 3. 根据 project member ID 得到对应email
    for(String memberID in membersID) {
        def responseMember=sendGetRequest("/api/v4/users/${memberID}")
        def jsonMember=jsonParsing(responseMember)
        emailList.append(jsonMember.email).append(";")
    }

    // 4. 根据group name 得到group member detail
    def responseGroupMembers=sendGetRequest("/api/v4/groups/${groupName}/members")
    def jsonGroupMembers=jsonParsing(responseGroupMembers)
    def groupMembersID=jsonGroupMembers.id as String[]

    // 5. 根据 group member ID 得到对应 email
    for(String memberID in groupMembersID) {
        def responseMember=sendGetRequest("/api/v4/users/${memberID}")
        def jsonMember=jsonParsing(responseMember)
        emailList.append(jsonMember.email).append(";")
    }   
    return emailList
}

/**
 * Send notifications based on build status string
 */
def call(String buildStatus = 'STARTED', displayName='') {

  echo "========================SEND EMAIL================================="

if ("${DO_SENDEMAIL}".toBoolean())
{
    // build status of null means successful
  buildStatus = buildStatus ?: 'SUCCESS'
  PROJECT_NAME = "${PROJECT_NAME}" ?: 'null'
  // Default values
  def subject = "${buildStatus}:Jenkins Pipeline: [${PROJECT_NAME}]-[${env.JOB_NAME}] -- Ver:${displayName}"
  // def body = """<p>${buildStatus}: Job '${env.JOB_NAME} [${env.BUILD_DISPLAY_NAME}]':</p>
  //   <p>Check console output at &QUOT;<a href='${env.BUILD_URL}'>${env.JOB_NAME} [${env.BUILD_DISPLAY_NAME}]</a>&QUOT;</p>"""

  if (MAILRECIPIENTS ?.trim()) // empty or null
   { 
     echo "MAILRECIPIENTS:${MAILRECIPIENTS}"
   }
   else
   { //如果默认收件地址为空，Email地址来自gitlab group 以及 gitlab project下面的member
     MAILRECIPIENTS=getEmailList("${GIT_URL}")
     echo "MAILRECIPIENTS_UPDATED:${MAILRECIPIENTS}"
   }
 
  emailext (    
      mimeType: 'text/html', 
      attachLog: true,
      compressLog: false,
      subject: "${subject}",
      body: '''${SCRIPT, template="groovy-html.template"}''',      
      to: "${MAILRECIPIENTS}",
      recipientProviders: [[$class: 'DevelopersRecipientProvider']]
    )
}
else
{
    echo "booleanParam 'DO_SENDEMAIL' is false, skipping sending email..."
}  
  echo "=================================DONE================================="

}